<?php

namespace app\common\model;

use think\facade\Db;
use app\common\model\FinanceStat;

class Power
{
    /**
     * 处理电费订单状态回调更新.
     */
    public static function handleNotify($order, $update)
    {
        Db::name('power_order')
            ->where('id', $order['id'])
            ->update($update);

        if (3 == $update['supplier_status']) {  // 充值成功
            // 成功了，插入财务明细
            FinanceStat::addSuccessRecord([
                'order_id' => $order['sub_order_id'],
                'order_type' => PRODUCT_POWER_SERV,
                'settle_type' => $order['settle_type'],
                'amount' => $order['amount'],
                'sale_price' => $order['sale_price'],
                'settle_price' => $order['settle_price'],
                'supplier_price' => $order['supplier_price'],
                'profit' => $order['sale_price'] - $order['settle_price'],
                'platform_profit' => $order['settle_price'] - $order['supplier_price'],
                'supplier_id' => $order['supplier_id'],
                'agent_id' => $order['agent_id'],
                'remark' => '充值成功',
            ]);
        }

        if (!empty($order['notify_url'])) {
            $agent = Db::name('agent')
                ->field('app_key, app_secret')
                ->where('id', $order['agent_id'])
                ->find();
            Db::name('power_notify_agent')
                ->insert([
                    'order_id' => $order['order_id'],
                    'notify_url' => $order['notify_url'],
                    'params' => json_encode([
                        'order_id' => strval($order['order_id']),
                        'out_order_id' => $order['out_order_id'],
                        'status' => $update['supplier_status'],
                        'card_no' => $order['card_no'],
                        'amount' => fen2yuan($order['amount']),
                        'app_key' => $agent['app_key'],
                        'app_secret' => $agent['app_secret'],
                    ]),
                    'status' => 1,
                    'send_time' => time(),
                    'result' => '',
                ]);
        }
    }
}
